package com.example.myapplication.view

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.FrameLayout
import com.example.myapplication.databinding.ViewGardenBoxTipsBinding
import com.example.myapplication.shortvideo.utils.DisplayUtils

/**
 * @description:
 *
 * @author: wangrongfeng
 *
 * @create: 2023-08-27 11:38
 **/
class GardenBoxTipView
@JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    var countDownTime = 0
    var frameLayout : FrameLayout?=null
   val mBinding: ViewGardenBoxTipsBinding
    init {
        mBinding =  ViewGardenBoxTipsBinding.inflate(LayoutInflater.from(context), this, true)
    }

    fun show(layout:FrameLayout){
        this. frameLayout= layout
        val boxTipLayoutParams = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT
        )
        boxTipLayoutParams.gravity = Gravity.END or   Gravity.BOTTOM
        boxTipLayoutParams.marginEnd = DisplayUtils.dp2px( 65)
        boxTipLayoutParams.bottomMargin = DisplayUtils.dp2px( 90)
        layout.addView(this,boxTipLayoutParams)
    }

    fun startTime(time: Int) {
        countDownTime = time
        mBinding.tvTips.text = "${countDownTime}s后宝箱消失，快点击领取"
        mHandler.sendEmptyMessageDelayed(1, 1000)
    }

    private val mHandler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            if (msg.what == 1) {
                countDownTime--
                if(countDownTime>0){
                    mBinding.tvTips.text = "${countDownTime}s后宝箱消失，快点击领取"
                    sendEmptyMessageDelayed(1, 1000)
                }else{
                    frameLayout?.removeView(this@GardenBoxTipView)
                }
            }
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        mHandler.removeMessages(1)
    }

}